package es.cazadoresmadridejos.beans.controller;

import org.apache.log4j.Logger;
import org.apache.log4j.spi.RootLogger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import es.cazadoresmadridejos.beans.manager.partner.PartnerManager;
import es.cazadoresmadridejos.beans.manager.reason.ReasonManager;
import es.cazadoresmadridejos.beans.manager.session.UserPreferences;
import es.cazadoresmadridejos.model.Reason;
import es.cazadoresmadridejos.objs.security.User;


@Controller
public class IndexController {

	@Autowired private ReasonManager reasonManager;
	@Autowired private PartnerManager partnerManager;
	@Autowired(required=false) private UserPreferences userPreferences;
	
	private Logger logger = RootLogger.getLogger(this.getClass());
	
	@RequestMapping(value="/index.html",method=RequestMethod.POST)
	public ModelAndView loginSubmit(
			){
		ModelAndView mv = new ModelAndView();
		
		logger.info("Application entry");
		
		return mv;
	}
	
	@RequestMapping(value="/index.html",method=RequestMethod.GET)
	public ModelAndView index(
			@RequestParam(value="date",required=false) Long year){
		userPreferences.init();
		ModelAndView mv = new ModelAndView();
		
		logger.info("Change date.");
		
		User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		user.setPartner(partnerManager.get(user.getPartner().getId()));
		if(year != null){
			Reason reason = reasonManager.get(year);
			user.getPartner().setSelectedReason(reason);
			partnerManager.save(user.getPartner());
		}
		
		mv.addObject("partner", user.getPartner());
		mv.addObject("reasons", reasonManager.findAll());
		
		return mv;
	}
	
}

